import {
	setAsyncFunWait,
	setParseFunTime
} from '@/setupproject/TOOLS_FUN'

import {
	payment
} from '@/setupproject/PAYS_FUN'

import {
	getUserBalanceOrderConfirmApi,
	app_user_balance_order_confirm,
	getUserPayNoticeApi,
} from '@/setupproject/INTERFACE'

export default {
	data() {
		return {
			isShowPayNotice: false,
		}
	},
	computed: {
		// 返回APP时小程序所携带的参数
		backAppParams() {
			return this.$store.getters.backAppParams;
		},
	},
	watch: {
		async backAppParams(v, ov) {
			let apiType = this.apiType || this.apiOrderType || this.apiPayTypeVal;
			
			if (apiType && (this.backAppParams.type == apiType) && v.balance_order_num && (v
					.balance_order_num !== ov.balance_order_num)) {

				// 获取订单支付结果
				await this.getPayConfirm(this.backAppParams.balance_order_num, apiType, this.backAppParams
					.orign_scene);

			}

		},

	},

	methods: {
		async getPayNotice() {
			if(uni.getStorageSync('PayNoticeTime') === setParseFunTime(new Date(), 'YYYY-mm-dd')) return;
			
			const {
				data
			} = await getUserPayNoticeApi();
			
			this.isShowPayNotice = data.is_notice;
			
			if(data.is_read) {
				uni.setStorage({
					key: 'PayNoticeTime',
					data: setParseFunTime(new Date(), 'YYYY-mm-dd')
				});
			}
			
			if(this.isShowPayNotice) this.$store.commit('SHOW_RECHARGE_SET_FUN', true);
		},
		
		/**
		 * @Description: 第三方微信小程序支付回调方法
		 * @param orderInfoDats  订单信息
		 * @param payType 当前充值方式
		 * @param orign_scene 触发场景：user 我的页面（充值）
		 * @return null
		 */
		async launchMPToPayFun(orderInfoDats, payType, orign_scene = '') {
			
			let apiType = this.apiOrderType || this.apiPayTypeVal;
			try {
				if (orderInfoDats.is_need_wx_pay) {
					// app支付方式lianlianpay/mbpay_jump_mini特殊处理跳转我的页面
					// #ifdef APP-PLUS
					if(!['user', 'bag', 'specialOfferZone'].includes(orign_scene) && ['lianlianpay', 'mbpay_jump_mini'].includes(payType)) {
						const [em, modal] = await uni.showModal({
							content: '是否先充值支付？',
						})
						
						// 是否允许重新点击
						this.submitLoading = false;
						
						if (!modal.confirm) return;
						
						// 是否关闭抽赏弹框
						this.isShowOrderUppop = false;
						
						// 调起充值弹框
						this.$refs.comRewardOrder.$refs.comRecharge.showInvestMoneySubmit();
						
						// 是否允许重新点击
						this.submitLoading = false;
						return;
					}
					// #endif
					
					// #ifdef APP-PLUS
					this.payBeInfos.balance_order_num = orderInfoDats.balance_order_num;
					this.payBeInfos.isPayBackSence = true;
					this.payBeInfos.type = apiType;
					payment(orderInfoDats, payType, apiType, orign_scene);
					// #endif
					// Android App拉起微信小程序提示bad param,
					// 主要是因为req.userName的值传错,
					// req.userName的值是小程序的原始ID,
					// 而不是appld,小程序之间的跳转是appld.
					// #ifdef MP-WEIXIN
					let appId = '';
					let path = '';
					
					// 小程序：adapay支付
					if(payType === 'adapay_mini') {
						appId = orderInfoDats.pay_config.wx_app_id;
						path = orderInfoDats.pay_config.miniapp_path;
					}
					
					// 小程序：易宝支付 & 米花支付
					if(['yeepay_wx', 'mbpay_jump_mini'].includes(payType)) {
						appId = orderInfoDats.pay_config.appId;
						path = orderInfoDats.pay_config.prePayTn;
					}
					
					uni.navigateToMiniProgram({
						appId,
						path,
						extraData: {
							...orderInfoDats.pay_config,
						},
						envVersion: 'release', // develop 开发版  trial 体验版  release 正式版
						success: res => {
							// 打开成功
							this.payBeInfos.type = apiType;
							this.payBeInfos.balance_order_num = orderInfoDats
								.balance_order_num;
							this.payBeInfos.isPayBackSence = true;
						},
						fail: err => {
							// 打开失败
							this.submitLoading = false
						}
					})
					// #endif

				} else {
					// 获取订单支付结果
					this.getPayConfirm(orderInfoDats.balance_order_num, apiType, orign_scene);
					this.submitLoading = false;
				}


			} catch (e) {
				this.submitLoading = false;
			}
		},

		/**
		 * @Description: 统一获取订单支付结果
		 * @param order_num 订单号
		 * @param type 订单类型
		 * @param orign_scene 触发场景：user 我的页面（充值）
		 * @return null
		 */
		async getPayConfirm(order_num, type, orign_scene) {
			const {
				data,
				msg,
				code,
			} = await getUserBalanceOrderConfirmApi({
				type,
				balance_order_num: order_num,
			});

			this.showGoodsOrder = false;
			this.submitLoading = false;

			if (code !== 200) {
				return uni.showToast({
					icon: "error",
					title: msg,
					duration: 1500,
				})
			}

			// 我的页面（充值）
			if (this.backAppParams.orign_scene === 'user') {
				// 关闭充值弹框
				this.showInvestMoneyUser = false;
				uni.showToast({
					icon: "success",
					title: msg,
					duration: 1500,
				})
			}

			if (data.pay_status && this.backAppParams.isReward) {
				// 抽赏
				await this.getRewardResFun(this.backAppParams.balance_order_num);
			} else if (data.pay_status && this.backAppParams.isCar) {
				// 赏袋
				await this.orderResSending(this.backAppParams.balance_order_num);
			} else if (data.pay_status) {
				// 其他
				await this.loadDataGetFun();
			}

			await this.$store.commit('SET_WATCH_PLAT_PARAMS', {
				balance_order_num: ''
			});
			await setAsyncFunWait(300);
			await (this.submitLoading = false);

			if (data && !data.pay_status) {
				// #ifdef MP-WEIXIN
				return uni.showToast({
					icon: "error",
					title: '支付未成功,请重新操作',
					duration: 2500,
				})
				// #endif

				// #ifdef APP-PLUS
				return uni.showToast({
					icon: "none",
					title: '支付未成功,请重新操作',
					duration: 2500,
				})
				// #endif
			}

			return;

		},

	},

}